var div_barChart = d3.select(".second");

var pTeams_bar = getTeams();

var padding_bar = {
	top: 25,
	left: 10,
	right: 20,
	bottom: 5
}

var div2 = document.getElementsByClassName("second")[0];
//获取div的宽高
var width_bar = div2.offsetWidth - padding_bar.left - padding_bar.right;
var height_bar = div2.offsetHeight - padding_bar.top - padding_bar.bottom - 20;

//每个大矩形的宽高
var rectwidth = width_bar / 8;
var rectheight = height_bar / 4;

var svg_barChart = div_barChart.append("svg")
	.attr("class", "svg_barChart")
	.attr("preserveAspectRatio", "xMidYMid meet")
	.attr("viewBox", "0 0 " + width_bar + " " + height_bar);

var g_allRect;

var scale_rect;

var thisteam, thisseason;

function DrawBar(team, season) {

	d3.select('.svg_barChart').selectAll('g').remove();
	div_barChart.selectAll('image').remove();

	g_allRect = svg_barChart.append("g")
		.attr("class", "allTeam");

	thisteam = team;
	thisseason = season;
	var filename = "data/AllSeason/NBA_" + season + "_Season.csv";

	d3.csv(filename, function(data) {
		var teamData = [], //所选球队的整个赛季的比赛
			k = 0,
			score = 0;
		for (var i = 0; i < data.length; ++i) {
			if (data[i].Team == team) {
				teamData[k++] = data[i];
				var s = Math.abs(data[i].Score - data[i].OpponentScore);
				if (s > score) {
					score = s;
				}
			}
		}

		//计算每个小矩形的宽高
		scale_rect = d3.scale.linear()
			.domain([1, score])
			.range([1, rectheight / 3 * 2]);

		var Team_bar = [], //去除所选球队的其他球队
			k = 0;
		for (var i = 0; i < pTeams_bar.length; ++i) {
			if (team != pTeams_bar[i].Team) {
				Team_bar[k++] = pTeams_bar[i];
			}
		}
		//所选球队与其他球队比赛结果，按球队分
		var Team_Results = [],
			index = 0;
		for (var i = 0; i < Team_bar.length; ++i) {
			var d = [],
				k = 0;
			for (var j = 0; j < teamData.length; ++j) {
				if (Team_bar[i].Team == teamData[j].Opponent) {
					d[k++] = teamData[j];
				}
			}
			Team_Results[index++] = d;
		}
		//将没有对位的删除
		var results = [];
		index = 0;
		for (var i = 0; i < Team_Results.length; ++i) {
			if (Team_Results[i].length != 0) {
				results[index++] = Team_Results[i];
			}
		}
		Team_Results = results;

		var g_Team = g_allRect.selectAll("g")
			.data(Team_Results)
			.enter()
			.append("g")
			.attr("class", function(d) {
				return d[0].Opponent + "_g";
			});

		DrawTeamRect(DrawGameRect, g_Team);
		DrawGameRect(g_Team, data);
		SetSign(team, season);

	}); //csv
}
//对位球队的矩形框
function DrawTeamRect(callback, g) {
	var rectAll = g.append("rect")
		.attr("class", function(d) {
			return d[0].Opponent + "_rect";
		})
		/*.transition()
		.duration(function(d, i) {
			var duration = 1000 * (1 / 30); //动画时长1秒，计算每一个矩形所用动画时间
			return duration;
		})
		.ease("linear")
		.delay(function(d, i) {
			return i * 1000 * (1 / 30);
		})*/
		.attr("x", function(d, i) {
			var col = i % 8;
			return padding_bar.left + col * rectwidth;
		})
		.attr("y", function(d, i) {
			var row = parseInt(i / 8);
			return padding_bar.left + row * rectheight;
		})
		.attr("width", rectwidth - 5)
		.attr("height", rectheight - 5)
		.attr("fill", getColor)
		.attr("opacity", 0.3)
		.attr("stroke", 'black')
		.attr("stroke-width", 2)
		.attr('stroke-opacity', 1);

	var TeamName = g.append("text")
		.transition()
		.duration(function(d, i) {
			var duration = 1000 * (1 / 30); //动画时长1秒，计算每一个矩形所用动画时间
			return duration;
		})
		.ease("linear")
		.delay(function(d, i) {
			return i * 1000 * (1 / 30);
		})
		.attr("x", function(d, i) {
			var col = i % 8;
			return padding_bar.left + col * rectwidth + rectwidth / 3;
		})
		.attr("y", function(d, i) {
			var row = parseInt(i / 8);
			return padding_bar.left + row * rectheight + 15;
		})
		.text(function(d) {
			for (var i = 0; i < pTeams_bar.length; ++i) {
				if (d[0].Opponent == pTeams_bar[i].Team) {
					return pTeams_bar[i].abb;
				}
			}
		})
		.attr("font-size", "12px");
}
//每场比赛的矩形框
function DrawGameRect(g, data) {
	g.each(function(d) {
		//获取球队矩形框的位置，大小
		var rect = d3.select(this)[0][0].firstChild;

		var rectx = parseInt(rect.attributes.x.value);
		var recty = parseInt(rect.attributes.y.value);

		var rectWidth = (rectwidth - 5) / 4;
		var rectHeight = rectheight - 5;

		var GameRect = d3.select(this).selectAll(".rect")
			.data(d)
			.enter()
			.append("rect")
			/*.transition()
			.duration(function(d, i) {
				var duration = 1000 * (1 / 30); //动画时长1秒，计算每一个矩形所用动画时间
				return duration;
			})
			.ease("linear")
			.delay(function(d, i) {
				return i * 1000 * (1 / 30);
			})*/
			.attr("x", function(p, i) {
				return rectx + i * rectWidth;
			})
			.attr("y", function(p, i) {
				var s = Math.abs(p.Score - p.OpponentScore);
				return recty + rectheight - scale_rect(s) - 6;
			})
			.attr("width", rectWidth - 5)
			.attr("height", function(d) {
				var s = Math.abs(d.Score - d.OpponentScore);
				return scale_rect(s);
			})
			.attr("fill", function(p, i) {
				if (p.Result == '负') {
					return 'red';
				} else return 'green';
			})
			.attr("opacity", .8)
			.attr("stroke", "black")
			.attr("stroke-width", .5)
			.on('click', function(d) {
				DrawTeamToTeam(d, data);
			})
			.on("mouseover", function(p) {
				d3.select(this).append("svg:title")
					.text(function(d) {
						var s = Math.abs(d.Score - d.OpponentScore);
						return "分差 ：" + s;
					});
			}); //mouseover
	}); //each 	
}

function getColor(d) {
	var Win = 0;
	for (var i = 0; i < d.length; ++i) {
		if (d[i].Result == '胜') {
			Win += 1;
		}
	}
	if (Win < (d.length / 2)) {
		return "red";
	} else if (Win == (d.length / 2)) {
		return 'white';
	} else return "green";
}

function SetSign(team, season) {
	console.log(team, season);
	var sign = ['red', 'green'];
	var k = 0;
	for (var i = 0; i < pTeams_bar.length; ++i) {
		if (pTeams_bar[i].Team == team) {
			k = i;
			break;
		}
	}

	//图例
	var signs = svg_barChart.selectAll('.sign')
		.data(sign)
		.enter()
		.append('rect')
		.attr('x', width_bar - 170)
		.attr('y', function(d, i) {
			return height_bar - 50 + 15 * i;
		})
		.attr('height', 10)
		.attr('width', 20)
		.attr('fill', function(d) {
			return d;
		});

	svg_barChart.selectAll('.sign')
		.data(sign)
		.enter()
		.append('g')
		.append('text')
		.attr('x', width_bar - 140)
		.attr('y', function(d, i) {
			return height_bar - 42 + 15 * i;
		})
		.text(function(d) {
			if (d == 'red') {
				return 'Lose';
			} else return 'Win';
		})
		.attr('font-size', 12);
}

function DrawTeamToTeam(d, data) {
	var Opponent = d.Opponent;
	var time = d.Time;
	var OpponentData;
	var TeamData = d;
	for (var i = 0; i < data.length; ++i) {
		if (data[i].Time == time && data[i].Team == Opponent) {
			OpponentData = data[i];
		}
	}

	//删除上一个图
	div_barChart.selectAll('g').remove();
	div_barChart.selectAll('rect').remove();
	div_barChart.selectAll('image').remove();

	svg_two.selectAll('g').remove();
	svg_two.selectAll('image').remove();

	DrawRose(OpponentData.Team, thisseason, 0, svg_two, true);

	var Teams = [];
	Teams[0] = TeamData.Team;
	Teams[1] = OpponentData.Team;
	
	selectTeamAndOpponent(Teams,thisseason);

	//整理两队数据 '助攻', '盖帽', '篮板', '犯规', '得分', '失误'
	var item = ['Assists', 'Block', 'Backboard', 'Foul', 'Score', 'Turnover'];
	var myextents = {};
	//取得每一项属性该赛季的最大最小值
	for (var i = 0; i < item.length; ++i) {
		myextents[item[i]] = d3.extent(data, function(d) {
			return +d[item[i]].split("%")[0];
		});
	}
	var radar = [];
	radar[0] = TeamData;
	radar[1] = OpponentData;
	
	var Teams_Radar = [];
	var index_radar = 0;
	for(var i =0;i<pTeams_bar.length;++i){
		if(pTeams_bar[i].Team == TeamData.Team){
			Teams_Radar[index_radar++] = pTeams_bar[i];
		}
	}
	for(var i =0;i<pTeams_bar.length;++i){
		if(pTeams_bar[i].Team == OpponentData.Team){
			Teams_Radar[index_radar++] = pTeams_bar[i];
		}
	}
	
	var radarDatas = [];
	//将两队数据整理
	for (var i = 0; i < radar.length; ++i) {
		var radardata = [];
		for (var j = 0; j < item.length; ++j) {
			radardata[j] = radar[i][item[j]];
		}
		radarDatas[i] = radardata;
	}
	//雷达图制作
	DrawRadar(radarDatas, myextents,Teams_Radar);
	//饼图绘制
	var pieTeam = [];
	var pieOpponent = [];

	pieTeam[0] = parseInt(TeamData.T_Hit) * 3;
	pieOpponent[0] = parseInt(OpponentData.T_Hit) * 3;

	pieTeam[1] = parseInt(TeamData.P_Hit) * 1;
	pieOpponent[1] = parseInt(OpponentData.P_Hit) * 1;

	pieTeam[2] = parseInt(TeamData.Score) - pieTeam[0] - pieTeam[1];
	pieOpponent[2] = parseInt(OpponentData.Score) - pieOpponent[0] - pieOpponent[1];
	drawPie(pieTeam, pieOpponent);

	var g_image = svg_barChart.append('g')
		.attr('calss', 'g_image');
	//添加两队图标
	g_image.selectAll('image')
		.data(Teams)
		.enter()
		.append('image')
		.attr("xlink:href", function(d) {
			for (var i = 0; i < pTeams_bar.length; ++i) {
				if (d == pTeams_bar[i].Team) {
					return "logo/" + pTeams_bar[i].abb + "_logo.svg";
				}
			}
		})
		.attr("width", 80 + "px")
		.attr("height", 80 + "px")
		.attr('x', function(d, i) {
			return padding_bar.left + 50 + i * 300;
		})
		.attr('y', padding_bar.top - 25);

	//主客场
	var Homes = [];
	Homes[0] = TeamData.Home;
	Homes[1] = OpponentData.Home;
	g_image.selectAll('text')
		.data(Homes)
		.enter()
		.append('text')
		.attr('x', function(d, i) {
			if (i == 0) {
				return padding_bar.left + 140;
			} else {
				return padding_bar.left + 180 + i * 150;
			}

		})
		.attr('y', padding_bar.top + 25)
		.text(function(d) {
			return d;
		});

	//比赛时间
	g_image.append('text')
		.attr('x', padding_bar.left + 200)
		.attr('y', padding_bar.top + 25)
		.text(function() {
			console.log(OpponentData);
			return OpponentData.Time;
		});



	//Assists,Block,Backboard,Foul,Home,Score,Turnover,Steals,P_Shot/P_Hit,S_Shot/S_Hit,T_Shot/T_Hit
	//制作对偶图
	var Iteams = ['Score', 'Assists', 'Block', 'Forecourt', 'Backcourt', 'Foul', 'Turnover', 'Steals',
		'Penalty', 'Shoot', 'Threes'
	];

	var IteamsData = [];
	for (var i = 0; i < Iteams.length; ++i) {
		var d = {};
		d.IteamName = Iteams[i];
		d.Data = [];
		d.Data[0] = TeamData[Iteams[i]];
		d.Data[1] = OpponentData[Iteams[i]];
		IteamsData[i] = d;
	}
	var g_text = svg_barChart.append('g')
		.attr('calss', 'g_text');

	var g_rect = svg_barChart.append('g')
		.attr('class', 'g_rect');

	for (var j = 0; j < IteamsData.length; ++j) {
		var IteamData = IteamsData[j];
		//属性标签
		g_text.append('text')
			.attr('x', function(d) {
				return padding_bar.left + 210;
			})
			.attr('y', function(d) {
				return padding_bar.top + 60 + j * 20;
			})
			.text(function() {
				var pitems = getSigns();
				for (var i = 0; i < pitems.Chinese_name.length; ++i) {
					if (IteamData.IteamName == pitems.English_name[i]) {
						return pitems.Chinese_name[i];
					}
				}

			})
			.attr('font-size', 12);
		//球队矩形
		g_rect.selectAll('.rect')
			.data(IteamData.Data)
			.enter()
			.append('rect')
			.attr('x', function(d, i) {
				if (i == 0) {
					if (Iteams[j] == 'Penalty' || Iteams[j] == 'Shoot' || Iteams[j] == 'Threes') {
						return padding_bar.left + 180 - d * 100;
					} else {
						return padding_bar.left + 180 - d;
					}
				} else {
					if (Iteams[j] == 'Penalty' || Iteams[j] == 'Shoot' || Iteams[j] == 'Threes') {
						return padding_bar.left + 120 + i * 150;
					} else {
						return padding_bar.left + 120 + i * 150;
					}
				}


			})
			.attr('y', function(d) {
				return padding_bar.top + 50 + j * 20;
			})
			.attr('height', 15)
			.attr('width', function(d) {
				if (Iteams[j] == 'Penalty' || Iteams[j] == 'Shoot' || Iteams[j] == 'Threes') {
					return d * 100;
				} else return d;
			})
			.attr('stroke', 'black')
			.attr('fill', 'red')
			.attr('stroke-width', 2)
			.attr('opacity', function(d, i) {
				if (i == 0) {
					if (parseFloat(d) > parseFloat(IteamData.Data[1])) {
						return 1;
					} else {
						return 0.5;
					}

				} else {
					if (parseFloat(d) > parseFloat(IteamData.Data[0])) {
						return 1;
					} else {
						return 0.5;
					}
				}
			});

		//属性具体数值
		g_rect.selectAll('.text')
			.data(IteamData.Data)
			.enter()
			.append('text')
			.attr('x', function(d, i) {
				if (i == 0) {
					if (Iteams[j] == 'Penalty' || Iteams[j] == 'Shoot' || Iteams[j] == 'Threes') {
						return padding_bar.left + 155 - d * 100;
					} else {
						return padding_bar.left + 155 - d;
					}
				} else {
					if (Iteams[j] == 'Penalty' || Iteams[j] == 'Shoot' || Iteams[j] == 'Threes') {
						return padding_bar.left + 130 + i * 150 + parseFloat(d) * 100;
					} else {
						return padding_bar.left + 130 + i * 150 + parseInt(d);
					}
				}
			})
			.attr('y', function(d, i) {
				return padding_bar.top + 60 + j * 20;
			})
			.text(function(d, i) {
				if (Iteams[j] == 'Penalty' || Iteams[j] == 'Shoot' || Iteams[j] == 'Threes') {
					return parseFloat(d).toFixed(1) * 100 + '%';
				} else {
					return d;
				}
			})
			.attr('font-size', 12);
	}
}

function drawPie(team, opponent) {

	var items =['三分','罚球','两分'];

	var pie = d3.layout.pie();

	var pieData = [];
	pieData[0] = team;
	pieData[1] = opponent;
	
	
	var outerRadius = 50; //外半径
	var innerRadius = 0; //内半径，为0则中间没有空白
	
	var arc = d3.svg.arc() //弧生成器
		.innerRadius(innerRadius) //设置内半径
		.outerRadius(outerRadius); //设置外半径

	var colors = ['#1f77b4','#ff7f0e','#2ca02c'];

	for (var i = 0; i < pieData.length; ++i) {
		var sum = parseInt(pieData[i][0] + pieData[i][1] + pieData[i][2]);
		var arcs = svg_barChart.selectAll(".g_BarChart_Rose")
			.data(pie(pieData[i]))
			.enter()
			.append("g")
			.attr("transform", "translate(" + (width_bar / 17 * (11 + i * 4)) + "," + (height_bar / 9 * 7) + ")");

		arcs.append("path")
			.attr("fill", function(d, j) {
				return colors[j];
			})
			.attr("d", function(d) {
				return arc(d);
			})
			.on('mouseover',function(d){
				var per =  parseFloat(parseInt(d.data) / sum) * 100;
				d3.select(this).append("svg:title")
					.text((per.toFixed(1) ) + '%');
			});
			
		arcs.append("line")
			.attr("stroke", "black")
			.attr("x1", function(d){
				return arc.centroid(d)[0] * 2;
			})
			.attr("y1", function(d){
				return arc.centroid(d)[1] * 2;
			})
			.attr("x2", function(d){
				return arc.centroid(d)[0] * 2.5;
			})
			.attr("y2",function(d){
				return  arc.centroid(d)[1] * 2.5;
			});

		arcs.append("text")
			.attr("transform", function(d){
				var x = arc.centroid(d)[0] * 2.8; //文字的x坐标
				var y = arc.centroid(d)[1] * 2.8; //文字的y坐标
				return "translate(" + x + ',' + y + ")";
			})
			.attr("fill", "black")
			.attr("text-anchor", "middle")
			.attr('font-size',10)
			.text(function(d,i){
				return items[i];
			});


	}

}
